
// 数字映射表
const DIGITS: [&str; 10] = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
const UNITS: [&str; 4] = [ "仟", "佰", "拾",""];
const SECTIONS: [&str; 4] = ["", "万", "亿", "万亿"];

/// 转换数字为中文大写（支持最大 16 位整数 + 2 位小数）
pub fn number_to_chinese(mut num: String) -> Result<String, String> {
    // 预处理输入
    let (integer_part, decimal_part) = parse_number(&mut num)?;

    // 转换整数部分
    let mut result = convert_integer(&integer_part)?;

    // 转换小数部分
    result += &convert_decimal(&decimal_part)?;

    Ok(result)
}

/// 解析数字输入
fn parse_number(num: &mut String) -> Result<(String, String), String> {
    // 处理逗号并验证格式
    num.retain(|c| c != ',' && c != '_');
    if num.is_empty() || num.chars().filter(|c| *c == '.').count() > 1 {
        return Err("无效数字格式".into());
    }

    // 分割整数和小数部分
    let parts: Vec<&str> = num.split('.').collect();
    let (integer, decimal) = (
        parts[0].trim_start_matches('0').to_string(),
        parts.get(1).unwrap_or(&"").to_string(),
    );

    // 验证长度限制
    if integer.len() > 16 || decimal.len() > 2 {
        return Err("数字超出处理范围（最多16位整数+2位小数）".into());
    }

    Ok((if integer.is_empty() { "0".into() } else { integer }, decimal))
}

/// 转换整数部分
fn convert_integer(integer: &str) -> Result<String, String> {
    let mut result = String::new();
    let chars: Vec<char> = integer.chars().rev().collect();

    let max_chunk_count = chars.len() / 4;
    // 按每4位分段处理
    for (i, chunk) in chars.chunks(4).enumerate() {
        let mut section = convert_chunk(chunk)?;
        if !section.is_empty() {
            section += SECTIONS[i % 4];
            if i != max_chunk_count && (chunk.len() ==4 && chunk[3]=='0' ){
                section.insert_str(0,"零");
            }
            result = section + &result;
        }
    }

    // 处理全零情况
    if result.is_empty() {
        Ok("零元".into())
    } else {
        Ok(result + "圆")
    }
}

/// 转换4位数字组
fn convert_chunk(chunk: &[char]) -> Result<String, String> {
    let mut res = String::new();
    let mut last_non_zero = false;
    let mut buf = ['0';4];
    let chunk = if chunk.len() < 4 {
        chunk.iter()
            .enumerate()
            .for_each(|(i, c)| buf[i] = *c);
        &buf
    }else{
        chunk
    };



    for (pos, &c) in chunk.iter().rev().enumerate() {
        let n = c.to_digit(10).ok_or("包含非数字字符")? as usize;

        // 处理零的显示规则
        if n == 0 {
            if last_non_zero {
                res += DIGITS[0];
                last_non_zero = false;
            }
        } else {
            res += DIGITS[n];
            res += UNITS[pos % 4];
            last_non_zero = true;
        }
    }

    // 去除结尾的零
    Ok(res.trim_end_matches('零').to_string())
}

/// 转换小数部分
fn convert_decimal(decimal: &str) -> Result<String, String> {
    let mut res = String::new();
    let chars: Vec<char> = decimal.chars().take(2).collect();

    for (i, &c) in chars.iter().enumerate() {
        let n = c.to_digit(10).ok_or("小数部分包含非数字字符")? as usize;
        if n > 0 {
            res += DIGITS[n];
            res += match i {
                0 => "角",
                1 => "分",
                _ => unreachable!()
            };
        }
    }

    if res.is_empty() {
        Ok("整".into())
    } else {
        Ok(res)
    }
}

// 测试用例
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_conversions() {
        assert_eq!(number_to_chinese("1234.56".into()).unwrap(), "壹仟贰佰叁拾肆元伍角陆分");
        assert_eq!(number_to_chinese("10000000".into()).unwrap(), "壹仟万元整");
        assert_eq!(number_to_chinese("0.05".into()).unwrap(), "零元伍分");
        assert_eq!(number_to_chinese("1002000300".into()).unwrap(), "壹拾亿零贰佰万零叁佰元整");
    }
}


fn main() {
    println!("{}",number_to_chinese("496712.99".into()).unwrap());
}
